<template>
  <div class="container">
    <!-- 图表容器 -->
    <div class="wrap">
      <div ref="chartContainer1" class="chart"></div>
      <div ref="chartContainer2" class="chart"></div>
    </div>

    <div class="wrap">
      <div ref="chartContainer3" class="chart"></div>
      <!-- 信息面板 -->
      <div class="info-panel">
        <img
          src="../images/13118080665_358104652.png"
          alt="Motor Image"
          class="motor-image"
        />
        <div class="info-text">
          <span class="tip">电机剩余寿命:</span>
          <span class="remaining-life">{{ message }} 小时</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { markRaw } from "vue";
import * as echarts from "echarts";
import axios from "axios";
import { ElMessageBox } from "element-plus";
import { WarningFilled } from "@element-plus/icons-vue";
// 数值过滤函数，保留两位小数
export function numFilter(value) {
  return Number(value).toFixed(2);
}

export default {
  data() {
    return {
      xData1: [], // 更新时间
      xData2: [], // 更新时间
      xData3: [], // 更新时间
      speedData: [], // 速度
      placeData: [], // 位移
      addspeedData: [], // 加速度
      message: "",
      isMessageBoxShow: false,
    };
  },
  created() {
    // 每2秒获取一次剩余寿命
    let timeTicket = setInterval(() => {
      this.getRlife();
    }, 2000);
  },
  mounted() {
    // 初始化图表
    this.initChart1();
    this.initChart2();
    this.initChart3();
    // 添加窗口大小改变事件监听器
    window.addEventListener("resize", this.resizeCharts);
  },
  beforeDestroy() {
    // 移除窗口大小改变事件监听器
    window.removeEventListener("resize", this.resizeCharts);
  },
  methods: {
    // 获取剩余寿命
    getRlife() {
      try {
        axios.get("/v1/test/getrlife", { params: { code: 1 } }).then((res) => {
          this.message = numFilter(res.data.data);
        });
      } catch (error) {
        console.error(error);
      }
    },
    // 初始化图表1
    initChart1() {
      this.chart1 = echarts.init(this.$refs.chartContainer1);
      this.chart1.setOption(
        this.getChartOption("振动速度折线图", "速度", "red")
      );
      this.fetchAndSetData(
        this.chart1,
        "wz_velocity",
        this.speedData,
        this.xData1
      );
      this.startUpdatingData(
        this.chart1,
        "wz_velocity",
        this.speedData,
        this.xData1
      );
    },
    // 初始化图表2
    initChart2() {
      this.chart2 = echarts.init(this.$refs.chartContainer2);
      this.chart2.setOption(
        this.getChartOption("振动位移折线图", "位移", "green")
      );
      this.fetchAndSetData(
        this.chart2,
        "wz_displacement",
        this.placeData,
        this.xData2
      );
      this.startUpdatingData(
        this.chart2,
        "wz_displacement",
        this.placeData,
        this.xData2
      );
    },
    // 初始化图表3
    initChart3() {
      this.chart3 = echarts.init(this.$refs.chartContainer3);
      this.chart3.setOption(
        this.getChartOption("振动加速度折线图", "加速度", "blue")
      );
      this.fetchAndSetData(
        this.chart3,
        "wz_addSPeed",
        this.addspeedData,
        this.xData3
      );
      this.startUpdatingData(
        this.chart3,
        "wz_addSPeed",
        this.addspeedData,
        this.xData3
      );
    },
    // 获取图表配置选项
    getChartOption(titleText, seriesName, color) {
      return {
        title: { text: titleText },
        legend: {
          data: [seriesName],
          backgroundColor: "#f5f5f5",
          borderColor: "#ccc",
          borderWidth: 1,
        },
        xAxis: {
          data: [],
          splitLine: { show: true, lineStyle: { type: "dashed" } },
          axisLabel: {
            rotate: 0, // 增加标签旋转角度，防止数据挤在一起
            fontSize: 10, // 调整字体大小
            margin: 10, // 增加标签与轴的距离
          },
        },
        yAxis: {
          type: "value",
          splitLine: { show: true, lineStyle: { type: "dashed" } },
          axisLabel: {
            fontSize: 12, // 调整字体大小
            margin: 10, // 增加标签与轴的距离
          },
        },
        grid: {
          left: "5%", // 调整图表左边距
          right: "5%", // 调整图表右边距
          bottom: "5%", // 增加底部边距，为旋转的标签留出空间
          containLabel: true, // 确保标签不会被裁剪
        },
        series: [
          {
            name: seriesName,
            type: "line",
            smooth: true, // 启用平滑效果
            data: [],
            lineStyle: { color, width: 2 }, // 增加线条宽度
            itemStyle: { color, borderColor: color, borderWidth: 1 }, // 增加数据点边框
            label: {
              show: true,
              position: "top",
              textStyle: { fontSize: 16, color: "#333" },
            },
          },
        ],
      };
    },
    // 获取并设置数据
    fetchAndSetData(chart, dataKey, dataArray, xData) {
      axios
        .get("/v1/test/getVibrateData", { params: { code: 1 } })
        .then((res) => {
          if (res.data.data) {
            const dataPoint = res.data.data[0];
            xData.push(dataPoint.updatetime);
            dataArray.push(dataPoint[dataKey]);
            chart.setOption({
              xAxis: { data: xData },
              series: [{ data: dataArray }],
            });
          }
        })
        .catch((err) => console.log(err));
    },
    // 开始更新数据
    startUpdatingData(chart, dataKey, dataArray, xData) {
      let timeTicket = setInterval(() => {
        axios
          .get("/v1/test/getVibrateData", { params: { code: 1 } })
          .then((res) => {
            if (res.data.data) {
              const dataPoint = res.data.data[0];

              switch (dataKey) {
                case "wz_velocity":
                  // 配置需要警报的振动速度阈值
                  if (dataPoint[dataKey] > -1 && !this.isMessageBoxShow) {
                    this.isMessageBoxShow = true;
                    ElMessageBox.alert("振动速度异常", "警告", {
                      confirmButtonText: "OK",
                      callback: () => {
                        this.isMessageBoxShow = false;
                      },
                      type: "error",
                      icon: markRaw(WarningFilled),
                    });
                  }
                  break;
                case "wz_displacement":
                  dataPoint[dataKey] = numFilter(dataPoint[dataKey]);
                  break;
                case "wz_addSPeed":
                  dataPoint[dataKey] = numFilter(dataPoint[dataKey]);
                  break;
              }

              dataArray.push(dataPoint[dataKey]);
              xData.push(dataPoint.updatetime);
              if (dataArray.length > 10) {
                dataArray.shift();
                xData.shift();
              }
              chart.setOption({
                xAxis: { data: xData },
                series: [{ data: dataArray }],
              });
            }
          })
          .catch((err) => console.log(err));
      }, 2000);
    },
    // 调整图表大小
    resizeCharts() {
      this.chart1.resize();
      this.chart2.resize();
      this.chart3.resize();
    },
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  padding: 0; /* 删除原有 padding */
  margin: 0; /* 删除原有 margin */
  height: 100vh; /* 设置容器高度为视口高度 */
  padding: 30px;
  box-sizing: border-box;
}
.wrap {
  width: 100%;
  display: flex;
  gap: 20px;
}
.chart {
  flex: 1;
  height: 300px; /* 固定高度为300px */
  margin: 0;
  border: 1px solid #ddd; /* 添加边框以区分图表区域 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.info-panel {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 300px;
}

.motor-image {
  width: 350px;
  height: auto;
  margin-right: 20px;
}
.tip {
  font-size: 20px;
}
.info-text {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.remaining-life {
  font-size: 60px;
  font-weight: 900;
  color: #0000ff;
  margin-top: 10px;
}
</style>